import {React, useState, useEffect} from "react";
import {Button, Form, Input, Toast} from "antd-mobile";
import './pay.css'
import {useTranslation} from "react-i18next";
import {LeftOutline} from "antd-mobile-icons";
import {useNavigate} from "react-router-dom";
import {user_recharge} from "@/request/api";

export default function Pay(){
    const { t, i18n } = useTranslation();
    const [money, setMoney] = useState('')
    const navigate = useNavigate();

    const submit = ()=>{
        if (!money){
            return Toast.show({
                icon: 'fail',
                content: t('cz7'),
                duration: 2500
            })
        }
        user_recharge({
            type: 1,
            num: money
        }).then(res =>{
            if (res.code == 0){
                Toast.show({
                    icon: 'success',
                    content: res.info,
                    duration: 2500
                })
                navigate('/Recharge')
            }
        })
    }
    function limitToTwoDecimalPlaces(value) {
        // 移除非数字和小数点的字符
        value += ''
        value = value.replace(/[^\d.]/g, '');

        // 限制只有一个小数点
        value = value.replace(/^(\d+)\./g, '$1.');
        value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');

        // 限制小数点后只能有两个数字
        value = value.replace(/(\d)\.(\d{3})/, '$1.$2');

        // 如果值为0开头，则允许输入小数点
        value = value.replace(/^0+(?=\d)/g, '');


        // 如果小数点后有超过两位数字，则去掉多余的数字
        var temp = value.split('.');
        if (temp.length > 1 && temp[1].length > 2) {
            value = temp[0] + '.' + temp[1].substr(0, 2);
        }
       return value
    }
    return (
        <>
        <div className='header'>
            <div className='backIcon' onClick={() => { navigate(-1) }}>
                <LeftOutline />
            </div>
            <p>{t('cz4')}</p>
        </div>
        <div className="recharge">
            <Form layout='horizontal'>
                <Form.Item label={t('cz8')} >
                    <Input value={money} placeholder={t("cz7")} onChange={(val)=>{
                        val = limitToTwoDecimalPlaces(val)
                        setMoney(val)
                    }} clearable />
                </Form.Item>
            </Form>
            <Button className="pay-money" shape='default' block color='primary' onClick={submit}>
                {t('ty3')}
            </Button>
        </div>
        </>
    )
}
